import React, { Component, createRef } from 'react'
import { Card, Table, Button, Modal, message, Popconfirm } from 'antd'
import { PAGE_SIZE } from '@/utils/constant'
import { reqAddRole, reqRoles, reqUpdateRole, reqUpdateListRole, reqRoleDelete } from '@/api'
import AddForm from "./addForm"
import AuthForm from "./authForm"
import UpdateForm from './updateForm'
import { formateDate } from "../../utils/dateUtils.js"
import { connect } from 'react-redux'
import { logout } from '@/redux/actions' 

/**
 * 角色管理路由组件
 */
 class Role extends Component {
  constructor(props) {
    super(props)
    this.state = {
      roles: [],  //所有角色的列表
      role: {},  //选中的对象
      loading: false,
      isShowAdd: false, //是否显示添加界面
      isShowAuth: false,  //是否显示设置权限界面
      isShowUpdate: false,  //是否显示更新的页面
      isShowDelete: false,
    }
    this.auth = createRef();
    this.updateRef = createRef();
    this.initColumn();
  }

  initColumn = () => {
    this.columns = [
      {
        title: '角色名称',
        dataIndex: 'name',
      },
      {
        title: '创建时间',
        dataIndex: 'create_time',
        render: (create_time) => formateDate(create_time)
      },
      {
        title: '授权时间',
        dataIndex: "auth_time",
        render: formateDate
      },
      {
        title: '授权人',
        dataIndex: "auth_name",
      },
      {
        title: '操作',
        width: 150,
        //dataIndex:"action",
        render: (role) => {
          return (
            <span style={{ display: 'flex' }}>
              {/* <LinkButton  onClick={() => this.showUpdate(role)}>修改</LinkButton> */}
              <Button style={{ color: '#1da57a' }} type="link" onClick={() => this.showUpdate(role)} block>修改</Button>
              <Popconfirm
                title="删除角色"
                description={`您确定删除该${role.name}角色吗？`}
                onConfirm={() => this.handleOk(role)}
                onCancel={() => this.setState({ isShowDelete: false })}
              >
                <Button style={{ color: '#1da57a' }} type="link" block>删除</Button>
              </Popconfirm>

            </span>
          )
        }
      },
    ]
  }

  //请求接口获取所有的角色列表
  getRoles = async () => {
    this.setState({
      loading: true
    })
    let result = await reqRoles();
    this.setState({
      loading: false
    })
    if (result.data.status === 0) {
      this.setState({
        roles: result.data.data
      })
    }
  }
  onRow = (role) => {
    return {
      onClick: (event) => {
        this.setState({
          role
        })
      }, // 点击行
    };
  }

  //添加角色回调
  addRole = () => {
    //进行表单的验证，只有通过了才能向下处理
    this.form.validateFields().then(async (values) => {
      //1.收集数据
      const { roleName } = values;
      this.form.resetFields();
      //2. 请求接口添加
      let result = await reqAddRole(roleName);
      console.log(result.data.data)
      if (result.data.status === 0) {
        message.success("添加角色成功");
        this.setState({
          isShowAdd: false
        })
        //this.getRoles();  //第一种更新列表数据的方法，重新请求回调
        // this.setState({
        //   roles:[...this.state.roles,...[result.data.data]]   //第二中更新列表数据的方法
        // })
        //第三种更新列表数据的方法,基于原来的状态更新数据  
        this.setState((state) => ({
          roles: [...state.roles, result.data.data]
        }))
      } else {
        message.error("添加角色失败")
      }
      //3.根据结果提示/更新显示
    }).catch(err => {
      //使用err的值，也可以自定义信息提示
      message.error(err)
    })
  }

  //更新角色回调
  updateRole = async () => {
    const role = this.state.role
    //取到子组件最新的menus
    const menus = this.auth.current.getMenus();
    role.menus = menus;
    role.auth_name = this.props.user.username  
    //请求更新
    const result = await reqUpdateRole(role);

    if (result.data.status === 0) {
      //如果当前更新的是自己的角色的权限，强制退出
      if (role._id === this.props.user.role._id) {
        this.props.logout();
        message.success("当前角色权限修改了,请重新登陆")
      } else {
        message.success("设置角色权限成功");
        this.getRoles();  //方法一
        this.setState({   //方法二
          // roles:[...this.state.roles],
          isShowAuth: false   //隐藏弹框
        })
      }
    }
  }

  //更新角色
  showUpdate = (role) => {
    this.roleObj = role
    this.setState({
      isShowUpdate: true
    })
  }

  //更新列表角色信息
  updateListRole = () => {
    const menus = this.updateRef.current.getMenus();
    this.form.validateFields().then(async (values) => {
      this.setState({
        isShowUpdate: false
      })
      const { roleName } = values;
      this.roleObj.menus = menus;
      this.roleObj.name = roleName
      this.roleObj.auth_name = this.props.user.username
      //清除表单的输入的数据
      this.form.resetFields();
      let res = await reqUpdateListRole(this.roleObj);
      if (res.data.status === 0) {
        message.success("更新角色信息成功");
        this.getRoles();
        this.setState({
          isShowUpdate: false
        })
      }
    })
  }

  //删除角色的回调函数
  handleOk = async (role) => {
    if (role.name === "admin") {
      message.error("角色为管理员不可删除")
    } else {
      let res = await reqRoleDelete(role._id);
      if (res.data.status === 0) {
        message.success("删除角色成功！");
        this.getRoles();
      }
    }

  }
  componentDidMount() {
    this.getRoles();
  }

  render() {
    const { roles, loading, role, isShowAdd, isShowAuth, isShowUpdate } = this.state
    const title = (
      <span>
        <Button type='primary' onClick={() => { this.setState({ isShowAdd: true }) }} style={{ marginRight: 10 }}>创建角色</Button>
        <Button type='primary' disabled={!role._id} onClick={() => { this.setState({ isShowAuth: true }) }}>设置角色权限</Button>
      </span>
    )
    return (
      <Card title={title}>
        <Table dataSource={roles} columns={this.columns} rowKey='_id' bordered pagination={{ defaultPageSize: PAGE_SIZE }}
          rowSelection={{ type: 'radio', selectedRowKeys: [role._id],onSelect:(role)=>{ this.setState({role})} }} onRow={this.onRow} loading={loading}
        />

        <Modal title="添加角色" cancelText="取消" okText="确定" open={isShowAdd} onOk={this.addRole} onCancel={() => {
          this.setState({ isShowAdd: false })
          this.form.resetFields();
        }}>
          <AddForm setForm={(form) => { this.form = form }}></AddForm>
        </Modal>
        <Modal title="设置角色权限" cancelText="取消" okText="确定" open={isShowAuth} onOk={this.updateRole} onCancel={() => {
          this.setState({ isShowAuth: false })
        }}>
          <AuthForm ref={this.auth} role={role}></AuthForm>
        </Modal>

        <Modal title="更新角色" cancelText="取消" okText="确定" open={isShowUpdate} onOk={this.updateListRole} onCancel={() => {
          this.setState({ isShowUpdate: false })
        }}>
          <UpdateForm role={this.roleObj} ref={this.updateRef} setForm={(form) => { this.form = form }}></UpdateForm>
        </Modal>

      </Card>
    )
  }
}

export default connect(
  state=>({user:state.user}),
  {logout}
  )(Role)
